<?php

namespace App\Http\Controllers\Wechat;

use App\Http\OrderStatus;
use App\Util\Result;
use App\Model\OrderDetail;
use App\Model\OrderList;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use EasyWeChat\Support\XML;
use Illuminate\Support\Facades\DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;

class WechatController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Application $weChat)
    {
        //
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $server = $weChat->server;

        $server->setMessageHandler(function ($message) {

            Log::info($message->MsgType);


            switch ($message->MsgType) {
                case 'event':
                    if($message->Event == 'CLICK'){

                        if($message->EventKey == 'V1001_CONTACT' ){

                            return '客服电话:400-6489155';
                        }
                        if($message->EventKey == 'V1001_ABOUT_US' ){

                            return '欢迎来到有品位旅游年卡！真诚为您服务！';
                        }
                    }
                    if($message->Event == 'subscribe'){
                        return "有品位旅游年卡欢迎您的到来，手持一卡畅游华夏！点击下方有品位进入热点景区查看更多相关信息。";
                    }


                    # 事件消息...
                    break;
                case 'text':
                    # 文字消息...
                    return "您好！欢迎关注我!";
                    break;
                case 'image':
                    # 图片消息...
                    break;
                case 'voice':
                    # 语音消息...
                    break;
                case 'video':
                    # 视频消息...
                    break;
                case 'location':
                    # 坐标消息...
                    break;
                case 'link':
                    # 链接消息...
                    break;
                // ... 其它消息
                default:
                    # code...
                    break;
            }
            // ...
        });


        Log::info('return response.');

        return $server->serve();
    }

    /**
     * @return Result|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function oauthCallbackWeb(){
        $config = [
            'app_id'  => env('WECHAT_APPID', 'wxbf705c2958cd8b95'),
            'secret'  => env('WECHAT_SECRET', '8fca8fa2cbe63fc667fce2e14484c667'),
            'oauth' => [
                'scopes'   => array_map('trim', explode(',', env('WECHAT_OAUTH_SCOPES', 'snsapi_login'))),
                'callback' => env('WECHAT_OAUTH_CALLBACK', 'http://www.youdianpinwei.com/wechat/oauth_callbackWeb'),
            ],
        ];
        $app = new Application($config);
        // 获取 OAuth 授权结果用户信息
        $oauth = $app->oauth;
        $user = $oauth->user();
        session(['wechat_userWeb' =>$user->toArray()]);
        $openid = session('wechat_userWeb')['id'];
        $model = DB::table('members')->where('pc_openid',$openid);
        //判断是否有pc_openid
        if (empty($model->count())) {
            $unionid = session('wechat_userWeb')['original']['unionid'];
            $sel = DB::table('members')->where('unionid',$unionid);
            //判断是否有unionid
            if (empty($sel->count())) {
                return redirect('/member/bindTel');
            } else {
                $sel->update(['pc_openid'=>$openid]);
                $member = $sel->first();
                if($member->status==2){
                    return Result::failure('帐号已被管理员禁用');
                } else {
                    session(['member'=>$member]);
                }
                return redirect('/member');
            }
        } else {
            $member = $model->first();
            if($member->status==2){
                return Result::failure('帐号已被管理员禁用');
            } else {
                session(['member'=>$member]);
            }
            return redirect('/member');
        }

    }

    public function homeWeb() {
        $config = [
            'app_id'  => env('WECHAT_APPID', 'wxbf705c2958cd8b95'),
            'secret'  => env('WECHAT_SECRET', '8fca8fa2cbe63fc667fce2e14484c667'),
            'oauth' => [
                'scopes'   => array_map('trim', explode(',', env('WECHAT_OAUTH_SCOPES', 'snsapi_login'))),
                'callback' => env('WECHAT_OAUTH_CALLBACK', 'http://www.youdianpinwei.com/wechat/oauth_callbackWeb'),
            ],
        ];
        $app = new Application($config);

        $oauth = $app->oauth;
        // 判断是否刚登录过
        if (empty(session('wechat_userWeb'))) {
            session(['target_urlWeb' =>'/member']);
            return $oauth->redirect();
        } else {
            $openid = session('wechat_userWeb')['id'];
            $model = DB::table('members')->where('pc_openid',$openid);
            //判断是否有pc_openid
            if (empty($model->count())) {
                $unionid = session('wechat_userWeb')['original']['unionid'];
                $sel = DB::table('members')->where('unionid',$unionid);
                //判断是否有unionid
                if (empty($sel->count())) {
                    $targetUrl = '/member/bindTel';
                } else {
                    $sel->update(['pc_openid'=>$openid]);
                    $member = $model->first();
                    session(['member'=>$member]);
                    $targetUrl = '/member';
                }
            } else {
                $member = $model->first();
                session(['member'=>$member]);
                $targetUrl = '/member';
            }
            return redirect($targetUrl);
        }
    }

    /**
     * 公众号菜单
     * czs
     */
    public function setMenu(Application $weChat) {
        $menu = $weChat->menu;
        $buttons = [
            [
                "name"       => "感创图书",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "首页 ",
                        "url"  => "http://www.senseitgroup.com/tushu/public/wap"
                    ],
                ],
            ],
            [
                "type" => "view",
                "name" => "首页 ",
                "url"  => "http://www.senseitgroup.com/tushu/public/wap"
            ],
            [
                "name"       => "会员服务",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "关于我们",
                        "url" => "http://www.senseitgroup.com/tushu/public/wap"
                    ],
                    [
                        "type" => "click",
                        "name" => "联系我们",
                        "key" => "V1001_CONTACT"
                    ],
                ],
            ],
        ];
        $menu->add($buttons);
    }



    public function oauthCallback(){
        $app = app('wechat');
        // 获取 OAuth 授权结果用户信息
        $oauth = $app->oauth;
        $user = $oauth->user();
        session(['wechat_user' =>$user->toArray()]);
        $openid = session('wechat_user')['id'];
        $model = DB::table('members')->where('openid',$openid);
        if (empty($model->count())) {
            return redirect('/wap/member/bindTel');
        } else {
            $member = $model->first();
            session(['member'=>$member]);
            return redirect(session('target_url'));
        }
    }

    public function home() {
        $app = app('wechat');
        $oauth = $app->oauth;
        // 判断是否刚登录过
        if (empty(session('wechat_user'))) {
            session(['target_url' =>'/wap']);
            return $oauth->redirect();
        } else {
            $openid = session('wechat_user')['id'];
            $model = DB::table('members')->where('openid',$openid);
            //判断是否有openid
            if (empty($model->count())) {
                $targetUrl = '/wap/member/bindTel';
            } else {
                $member = $model->first();
                session(['member'=>$member]);
                $targetUrl = '/wap';
            }
            return redirect($targetUrl);
        }
    }



    public function jsapi(Request $request){
        $id = $request->get('id');
        $payData = OrderList::onlinePay($id)->getData();

        if(!$payData || empty($payData)){
            return view('wechat.jsapi')->with('error','您的订单有误，请重新确认！')->with('json','');;
        }
        $app = app('wechat');

        $oauth = $app->oauth;
        // 未登录
        if (empty(session('wechat_user'))) {
            session(['target_url' =>'/wechat/jsapi']);
            return $oauth->redirect();
        }

        $user = session('wechat_user');

        $openid = $user['id'];

        $payment  = $app->payment;

        $orderNum = $payData->order_modify_num ? $payData->order_modify_num : $payData->order_num ;
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => '55茗果',
            'detail'           => '有品位旅游年卡',
            'out_trade_no'     => $orderNum,
            'total_fee'        => $payData->total_price*100,
            'notify_url'       => 'http://www.youdianpinwei.com/wechat/order-notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $openid,
        ];


        $order = new Order($attributes);

        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId);
            return view('wechat.jsapi')->with('json',$json);
        }
    }

    /**
     * web微信拼接二维码
     * czs
     */
    public function jsapiWeb(Request $request){
        $id = $request->get('id');
        $payData = OrderList::onlinePay($id)->getData();

        Log::info('paydata:'.$payData->order_num);
        $app = app('wechat');
        $payment = $app->payment;
        $orderNum = $payData->order_modify_num ? $payData->order_modify_num : $payData->order_num ;

        $attributes = [
            'body'             => '55茗果',
            'detail'           => '有品位旅游年卡',
            'out_trade_no'     => $orderNum,
            'total_fee'        => $payData->total_price*100,
            'trade_type'       =>'NATIVE',
            'product_id'       => $id,
            'notify_url'       => 'http://www.youdianpinwei.com/wechat/order-notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
        ];

        $order = new Order($attributes);

        $result = $payment->prepare($order);
        Log::info('result'.$result->code_url);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            return array(
                'success' => true,
                'data' => $result->code_url,
            );
        }
    }


    public function notify(){
        $app = app('wechat');
        $response = $app->payment->handleNotify(function($notify, $successful){
            if($successful){
                $orderNum = $notify->out_trade_no;
                $orderStatus = OrderList::where('order_num',$orderNum)->orWhere('order_modify_num',$orderNum)->value('status');
                if($orderStatus == OrderStatus::ORDER){
                    $data['status'] =  OrderStatus::DELIVE;
                    $data['pay_time'] = time();
                    $res = OrderList::where('order_num',$orderNum)->orWhere('order_modify_num',$orderNum)->update($data);
                    if($res === false){
                        return false;
                    }
                    else{
                        $order =  DB::table('order_lists')->where('order_num',$orderNum)->orWhere('order_modify_num',$orderNum)->select('id','member_id')->first();
                        $res = OrderDetail::deliveCard($order->id,$order->member_id);
                        if($res === false){
                            return $res;
                        }
                    }
                    // 你的逻辑
                    Log::info('微信回调');
                }
                else{
                    Log::info('重复回调');
                }
            }
            else{
                Log::info('支付失败');
            }

            return true; // 或者错误消息
        });
        return $response; // Laravel 里请使用：return $response;
    }

}
